//
//  NetworkTools.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/25.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import AFNetworking

enum SMHRequestMethed: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    //MARK: - 应用程序信息
    let appKey = "3255718741"
    let appSecret = "9f1fd359f78ab16e5b71b35b4ce343ea"
    let redirectURL = "http://www.baidu.com"
//    private let appKey = "3863118655"
//    private let appSecret = "b94c088ad2cdae8c3b9641852359d28c"
//    private let redirectURL = "http://www.baidu.com"
     /// 回调闭包
     typealias SMHRequestCallBack = (result: AnyObject?, error: NSError?) -> (Void)
    
    //设置单例
    static let sharedNetworkTools: NetworkTools = {
       let tools = NetworkTools(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //返回token字典
    private var tokenDict: [String: AnyObject]? {
        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
            return ["access_token": token]
        }
        return nil
    }
}

//AMRK: - 微博数据相关方法
extension NetworkTools {
    func loadStatus(since_id since_id: Int, max_id: Int,finished: SMHRequestCallBack) {
        var params = [String: AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        tokenRequest(.GET, urlString: urlStr, parameters: params, finished: finished)
    }
}

// MARK: - 发布微博
extension NetworkTools {
    func sendStatus(status: String, images: [UIImage], finished: SMHRequestCallBack) {
        var params = [String: AnyObject]()
        params["status"] = status
        if images.count == 0 {
            
            let urlStr = "https://api.weibo.com/2/statuses/update.json"
            tokenRequest(.POST, urlString: urlStr, parameters: params, finished: finished)
        } else {
            
            let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
            upload(urlStr, images: images, name: "pic", parameters: params, finished: finished)
        }
    }
    // - see[http://open.weibo.com/wiki/2/statuses/upload_pic](http://open.weibo.com/wiki/2/statuses/upload_pic)
//    private func uploadPicture(image: UIImage) -> String? {
//        let urlStr = "https://api.weibo.com/2/statuses/upload_pic.json"
//        let data = UIImagePNGRepresentation(image)
//        upload(urlStr, data: data!, name: "pic", parameters: nil) { (result, error) -> (Void) in
//            if error != nil {
//                print(error)
//                return
//            }
//            print(result)
//        }
//        return nil
//    }
}

// MARK: - 加载用户相关方法
extension NetworkTools {
    func loadUserInfo(uid: String, finished:SMHRequestCallBack) {
        var params = [String: AnyObject]()
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        params["uid"] = uid

        tokenRequest(.GET, urlString: urlStr, parameters: params, finished: finished)
    }
}

//MARK: - OAuth相关方法
extension NetworkTools {
///- see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)"
        return NSURL(string: urlString)!
    }
    
    
    //https://api.weibo.com/oauth2/authorize?client_id=700924480&redirect_uri=http://www.baidu.com
    func loadAccountToken(code: String, finished: SMHRequestCallBack) {
        
        let tokenUrl = "https://api.weibo.com/oauth2/access_token"
        let params: [String: AnyObject]? = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectURL]
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        request(SMHRequestMethed.POST, urlString: tokenUrl, parameters: params, finished: finished)
    
// 测试服务器返回数据的类型
//        responseSerializer = AFHTTPResponseSerializer()
        
//        POST(tokenUrl, parameters: params, success: { (_, result) -> Void in
//            let str = String(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            
//            print(str)
//            }, failure: nil)
        
    }

}

//MARK: - 封装AFN
extension NetworkTools {
    
    private func tokenRequest(methed: SMHRequestMethed, urlString: String, var parameters: [String: AnyObject]?, finished:SMHRequestCallBack) {
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token为空"]))
            return
        }
        
        request(methed, urlString: urlString, parameters: parameters, finished: finished)
    }
    
    /// 向 parameters 字典中追加 token 参数
    private func appendToken(inout parameters: [String: AnyObject]?) -> Bool {
        guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
            return false
        }
        
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        return true
    }
    
    /// 网络请求
    private func request(methed: SMHRequestMethed, urlString: String, parameters: [String: AnyObject]?, finished:SMHRequestCallBack) {
        
        let success = { (dataTask: NSURLSessionDataTask, result :AnyObject?) -> Void in
            finished(result: result, error: nil)
            }
        let failure = { (dataTAsk: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        if methed == SMHRequestMethed.GET {
            GET(urlString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, success: success, failure: failure)
        }
    }
    
    /// 上传文件
    private func upload(urlString: String,images: [UIImage], name: String, var parameters: [String: AnyObject]?, finished:SMHRequestCallBack) {
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token为空"]))
            return
        }
        
        let success = { (dataTask: NSURLSessionDataTask, result :AnyObject?) -> Void in
            finished(result: result, error: nil)
        }
        let failure = { (dataTAsk: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                var index = 0
                for image in images {
                    let data = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(data, name: name, fileName: "fileName\(index)", mimeType: "image/jpeg")
                    index++
                }
            }, success: success, failure: failure)
    }
}
